<?php
namespace Api\Controller;
use Think\Controller;
/**
 * 文章
 */
class CronController extends Controller
{
    protected $noCheck = [];

    function _initialize() {
    }

    public function member_no_gj()
    {
        $month_time = month_time(strtotime("-1 month"));
        $min_time = M('member_no_like')->min('create_time');
        if($min_time){
            $last_month = month_time(strtotime("-1 month"));
            $cur_period = getMonthNum(date('Y-m-d', $last_month[0]), date('Y-m-d', $min_time))+1;
            if($month_time[1] >= $min_time){
                $sql = "SELECT mn.*,sum(ml.like_num) as like_num FROM __MEMBER_NO__ as mn LEFT JOIN __MEMBER_NO_LIKE__ as ml ON mn.id=ml.member_no_id WHERE mn.id IS NOT NULL AND ml.create_time >={$month_time[0]} AND ml.create_time <={$month_time[1]} GROUP BY mn.id,ml.user_id ORDER BY like_num DESC,mn.like_time ASC,mn.id ASC LIMIT 0,10";
                $gj_users = M('')->query($sql);
                $date = date('Y年m月', $month_time[0]);
                if($gj_users){
                    foreach ($gj_users as $key => &$user) {
                        $gj_info = M('member_no_gj')->where(['date'=>$date, 'rank'=>($key+1)])->find();
                        if(empty($gj_info)){
                            $goods = M('member_no_goods')->where(['rank'=>($key+1)])->find();
                            if($goods){
                                $mg_id = $goods['id'];
                                $goods_name = $goods['goods_name'];
                                M('member_no_gj')->add([
                                    'user_id'       => $user['user_id'],
                                    'member_no'     => $user['member_no'],
                                    'date'          => $date,
                                    'period'        => $cur_period,
                                    'mg_id'         => $mg_id,
                                    'goods_name'    => $goods_name,
                                    'rank'          => ($key+1),
                                    'create_time'   => time(),
                                ]);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 自动确认收货
     * @return
     */
    public function auto_confirm_receipt()
    {
        set_time_limit(59);
        $page = S('auto_confirm_receipt_page');
        if(empty($page)){
            $page = 1;
        }
        $rows = 40;
        $order_list = M('order')->where(['pay_status'=>1, 'wu_status'=>1, 'status'=>2, 'logistics_type'=>['neq', ''], 'logistics_code'=>['neq', '']])->page($page, $rows)->field('id,uid,code,logistics_code,logistics_type,ctime')->select();
        if(empty($order_list) || count($order_list) < $rows){
            // 采用文件方式缓存数据300秒
            S('auto_confirm_receipt_page', 0, array('type'=>'file', 'expire'=>300));
        }else{
            // 采用文件方式缓存数据300秒
            S('auto_confirm_receipt_page', $page+1, array('type'=>'file', 'expire'=>300));
        }
        $confirm_time = time() - 86400*15;
        foreach ($order_list as $key => $order) {
            if($order['ctime'] < $confirm_time ){
                // 自动确认收货
                confirm_order_receipt($order['id']);
            }
            // $logistics = logistics_com($order['logistics_type']);
            // if($logistics){
            //     $logistics['logistics_name'] = $order['logistics_type'];
            //     $logistics['logistics_code'] = $order['logistics_code'];
            //     $result = queryExpress($logistics['com'], $order['logistics_code']);
            //     if($result['status'] == 1 && $result['state'] == 3){
            //         if(!empty($result['data'])){
            //             $ftime = [];
            //             foreach ($result['data'] as $key => $row){
            //                 $ftime[$key] = $row['time'];
            //             }
            //             array_multisort($ftime, SORT_DESC, $result['data']);
            //             $last_time = $result['data'][0]['time'];
            //             $last_time = strtotime($last_time);
            //             if($last_time && $last_time < $confirm_time){
            //                 // 自动确认收货
            //                 confirm_order_receipt($order['id']);
            //             }
            //         }
            //     }
            // }
        }
    }

    /**
     * 收货后无法售后添加返佣积分
     */
    public function auto_insert_commission()
    {
        set_time_limit(59);
        $page = S('auto_insert_commission_page');
        if(empty($page)){
            $page = 1;
        }
        $rows = 40;
        // 确认收货后多少天后返佣金
        $time = time() - 86400*7;
        $order_list = M('order')->where([
            'status'=>['in', ['3', '4']],
            'commission_status'=>1,
            'receipt_time'=>[['gt', 0], [['lt', $time]], 'AND'],
        ])->page($page, $rows)->select();
        if(empty($order_list) || count($order_list) < $rows){
            // 采用文件方式缓存数据300秒
            S('auto_insert_commission_page', 0, array('type'=>'file', 'expire'=>300));
        }else{
            // 采用文件方式缓存数据300秒
            S('auto_insert_commission_page', $page+1, array('type'=>'file', 'expire'=>300));
        }

        $userModel = M('user');
        foreach ($order_list as $key => $orderInfo) {
            $user = $userModel->where(['id'=>$orderInfo['uid']])->find();
            $order_up = [];
            if($user){
                $distribution_amount = $orderInfo['distribution_amount'] - $orderInfo['return_money'];
                // 分销
                if($user['first_leader']){
                    // 第一个上级
                    // $first_ratio = yzl_config('distribution.distribution_first_leader');
                    // $first_money = $distribution_amount*$first_ratio/100;
                    $first_money = M('commission_log')->where(['user_id'=>$user['first_leader'], 'order_id'=>$orderInfo['id']])->sum('money');
                    $first_money = round($first_money, 2);
                    if($first_money > 0){
                        money_log($user['first_leader'], $first_money, 1, $orderInfo['id']);
                        // M('order_commission')->add([
                        //     'user_id'       => $user['first_leader'],
                        //     'order_id'      => $orderInfo['id'],
                        //     'money'         => $first_money,
                        //     'status'        => 1,
                        //     'msg'           => '',
                        //     'pending_time'  => 
                        // ]);
                        $order_up = ['commission_status'=>4];
                    }
                    // 营业额
                    $userModel->where(['id'=>$user['first_leader']])->setInc('turnover', $orderInfo['cprice']);
                }
                if($user['second_leader']){
                    // 第二个上级
                    // $second_ratio = yzl_config('distribution.distribution_second_leader');
                    // $second_money = $distribution_amount*$second_ratio/100;
                    $first_money = M('commission_log')->where(['user_id'=>$user['second_leader'], 'order_id'=>$orderInfo['id']])->sum('money');
                    $second_money = round($second_money, 2);
                    if($second_money > 0){
                        money_log($user['second_leader'], $second_money, 1, $orderInfo['id']);
                        $order_up = ['commission_status'=>4];
                    }
                }
            }
            if(empty($order_up)){
                $order_up = ['commission_status'=>3];
            }
            M('order')->where(['id'=>$orderInfo['id']])->save($order_up);
        }
    }

    // /**
    //  * 自动返佣
    //  */
    // public function auto_commission()
    // {
    //     set_time_limit(59);
    //     $page = S('auto_commission_page');
    //     if(empty($page)){
    //         $page = 1;
    //     }
    //     $rows = 40;
    //     $commission_list = M('order_commission')->where(['status'=>1, 'pending_time'=>['elt', time()]])->page($page, $rows)->select();
    //     if(empty($commission_list) || count($commission_list) < $rows){
    //         // 采用文件方式缓存数据300秒
    //         S('auto_commission_page', 0, array('type'=>'file', 'expire'=>300));
    //     }else{
    //         // 采用文件方式缓存数据300秒
    //         S('auto_commission_page', $page+1, array('type'=>'file', 'expire'=>300));
    //     }
    //     foreach ($commission_list as $key => $row) {
    //         $res = money_log($row['user_id'], $row['money'], 1, $row['order_id']);
    //         if($res['status']){
    //             M('order_commission')->where(['id'=>$row['id']])->save(['status'=>2, 'msg'=>'ok']);
    //         }else{
    //             M('order_commission')->where(['id'=>$row['id']])->save(['status'=>3, 'msg'=>$res['msg']]);
    //         }
    //     }
    // }
}